package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.CustomException;
import com.example.dto.DishDto;
import com.example.entity.Category;
import com.example.entity.Dish;
import com.example.entity.DishFlavor;
import com.example.mapper.DishMapper;
import com.example.service.ICategoryService;
import com.example.service.IDishFlavorService;
import com.example.service.IDishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜品管理 服务实现类
 * </p>
 *
 * @author czx
 * @since 2022-04-28
 */
@Slf4j
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements IDishService {

    @Resource
    IDishFlavorService dishFlavorService;

    @Resource
    ICategoryService categoryService;

    /**
     * 分页查询
     *
     * @param page     页数
     * @param pageSize 页空间
     * @param name     菜名
     * @return 分页信息
     */
    @Override
    public Page<DishDto> page(int page, int pageSize, String name) {
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        //添加排序条件
        wrapper.orderByDesc(Dish::getCreateTime);
        //添加过滤条件
        wrapper.like(StringUtils.isNotEmpty(name), Dish::getName, name);

        Page<Dish> dishPage = baseMapper.selectPage(pageInfo, wrapper);

        PageDTO<DishDto> dishDtoPage = new PageDTO<>();

        //对象拷贝,前者拷贝给后者，并且排除records属性的拷贝
        BeanUtils.copyProperties(dishPage, dishDtoPage, "records");

        List<Dish> records = dishPage.getRecords();

        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            //分类id
            Long categoryId = item.getCategoryId();
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());

        dishDtoPage.setRecords(list);
        return dishDtoPage;
    }

    /**
     * 保存信息到dish表和dish_flavor表
     *
     * @param dishDto dish和flavor的数据传输对象
     * @return 保存结果
     */
    @Override
    @Transactional
    public boolean saveWithFlavor(DishDto dishDto) {
        //保存菜品的基本信息到菜品表dish
        int insert = baseMapper.insert(dishDto);
        //菜品id
        Long dishId = dishDto.getId();
        //菜品口味flavor
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors = flavors.stream().peek((item) -> item.setDishId(dishId)).collect(Collectors.toList());
        boolean saveBatch = dishFlavorService.saveBatch(flavors);
        return insert > 0 && saveBatch;
    }

    /**
     * 根据id查询
     *
     * @param id 菜品id
     * @return 查询结果
     */
    @Override
    public DishDto getByIdWithFlavor(Long id) {
        DishDto dishDto = new DishDto();
        Dish dish = baseMapper.selectById(id);
        BeanUtils.copyProperties(dish, dishDto);
        Category category = categoryService.getById(dish.getCategoryId());
        if (category != null) {
            //添加分类名称
            dishDto.setCategoryName(category.getName());
        }
        //添加菜品口味
        LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId, dish.getId());
        dishDto.setFlavors(dishFlavorService.list(dishFlavorLambdaQueryWrapper));
        return dishDto;
    }

    /**
     * 更新信息到dish表和dish_flavor表
     *
     * @param dishDto dish和flavor的数据传输对象
     * @return 更新结果
     */
    @Override
    @Transactional
    public boolean updateWithFlavor(DishDto dishDto) {
        int update = baseMapper.updateById(dishDto);
        //菜品id
        Long dishId = dishDto.getId();
        //菜品口味，先删除在插入,一个一个遍历修改太慢了
        List<DishFlavor> flavors = dishDto.getFlavors();
        LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId, dishId);
        dishFlavorService.remove(dishFlavorLambdaQueryWrapper);
        flavors = flavors.stream().peek((item) -> item.setDishId(dishId)).collect(Collectors.toList());
        boolean saveBatch = dishFlavorService.saveBatch(flavors);
        log.info("更新结果=》{}，{}", update, saveBatch);
        return update > 0 && saveBatch;
    }

    /**
     * 更新菜品状态
     *
     * @param status 菜品状态
     * @return 更新结果
     */
    @Override
    public boolean updateByStatus(int status, Long[] ids) {
        int i = 0;
        for (Long id : ids) {
            Dish dish = baseMapper.selectById(id);
            dish.setStatus(status);
            i += baseMapper.updateById(dish);
        }
        return i > 0;
    }


    /**
     * 菜品删除
     *
     * @param ids id
     * @return 删除结果
     */
    @Override
    public boolean removeWithDishFlavor(List<Long> ids) {
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(Dish::getId, ids);
        wrapper.eq(Dish::getStatus, 1);
        long count = this.count(wrapper);
        if (count > 0) {
            throw new CustomException("菜品还在售卖中，不能删除");
        }
        boolean b = this.removeBatchByIds(ids);
        LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishFlavorLambdaQueryWrapper.in(DishFlavor::getDishId, ids);
        boolean remove = dishFlavorService.remove(dishFlavorLambdaQueryWrapper);
        return b & remove;
    }

    /**
     * 查询菜品信息
     *
     * @param dish 菜品
     * @return 结果
     */
    @Override
    public List<DishDto> listWithDishFlavor(Dish dish) {
        Long categoryId = dish.getCategoryId();
        String name = dish.getName();
        log.info("DishServiceImpl.list(dish) --> categoryId = {}", categoryId);
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(categoryId != null, Dish::getCategoryId, categoryId);
        wrapper.like(StringUtils.isNotEmpty(name), Dish::getName, name);
        wrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getCreateTime);

        List<Dish> dishList = this.list(wrapper);

        return dishList.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            // 根据分类id查询分类对象
            Category category = categoryService.getById(item.getCategoryId());
            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            LambdaQueryWrapper<DishFlavor> flavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
            flavorLambdaQueryWrapper.eq(DishFlavor::getDishId,item.getId());
            List<DishFlavor> dishFlavorList = dishFlavorService.list(flavorLambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());
    }

}
